package com.lms.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-08-20 22:07
 * @Description:
 */
public class ZooKeeperClientTest {
    private static final String CONNECTION_STRING = "192.168.189.100:2181,192.168.189.101:2181,192.168.189.102:2181";
    private static final int SESSION_TIMEOUT = 2000;
    private ZooKeeper zk = null;


    /**
    * @Author 李孟帅
    * @Description 获取客户端连接
    * @Date 2020/8/20 
    **/
    @Before
    public void getConnection() throws IOException {
        zk = new ZooKeeper(CONNECTION_STRING, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event);
                try {
                    zk.getChildren("/",true);
                } catch (KeeperException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
    * @Author 李孟帅
    * @Description 创建节点
    * @Date 2020/8/20 
    **/
    @Test
    public void createNode() throws KeeperException, InterruptedException {
        String s = zk.create("/app1", "this is a test!".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(s);
    }

    /**
    * @Author 李孟帅
    * @Description 获取节点数据
    * @Date 2020/8/20 
    **/
    @Test
    public void getData() throws KeeperException, InterruptedException {
        byte[] data = zk.getData("/app1", false, null);
        System.out.println(new String(data));
    }

    /**
    * @Author 李孟帅
    * @Description 获取子节点
    * @Date 2020/8/20 
    **/
    @Test
    public void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zk.getChildren("/app1", true);
        for (String child : children) {
            System.out.println(child);
        }
        Thread.sleep(Long.MAX_VALUE);
    }
    /**
    * @Author 李孟帅
    * @Description 修改节点数据
    * @Date 2020/8/20 
    **/
    @Test
    public void setData() throws KeeperException, InterruptedException {
        Stat stat = zk.setData("/app1", "new data".getBytes(), -1);
        System.out.println(stat);
    }
    /**
    * @Author 李孟帅
    * @Description 删除节点
    * @Date 2020/8/20 
    **/
    @Test
    public void deleteNode () throws KeeperException, InterruptedException {
        zk.delete("/app1",-1);
    }

    /**
    * @Author 李孟帅
    * @Description 判断节点是否存在
    * @Date 2020/8/21 
    **/
    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat exists = zk.exists("/app2", true);
        System.out.println(exists);
    }


}
